<!--
 * @Descripttion:
 * @version:
 * @Author: tanghao1
 * @Date: 2021-01-21 15:39:19
 * @LastEditors: tanghao1
 * @LastEditTime: 2021-03-16 14:44:30
-->
<template>
  <el-dialog
    ref="refDlg"
    :title="detailData===''? '新增导航' : '编辑导航'"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :hide-func-bar="true"
    :before-close="clearForm"
    width="600px"
    custom-class="custom-dlg"
    @close="closeDialog"
  >
    <div>
      <el-form ref="form" :model="formData" :rules="formRules" size="mini" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="导航名称" prop="tabName" :rules="tabName">
              <el-input v-model="formData.tabName" size="mini" placeholder="请输入导航名称" maxlength="30" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否显示" prop="state" :rules="state">
              <el-switch
                v-model="formData.state"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col
            v-if="Number(formData.state || 0) ===1 && isLevelOne"
            :span="16"
          >
            <el-form-item
              label="显示位置"
              prop="showPlatform"
              :rules="[
                {required:Number(formData.state || 0) ===1 && isLevelOne,message:'请选择显示位置',trigger:'change'}
              ]"
            >
              <el-select
                v-model="formData.showPlatform"
                multiple
                clearable
                style="width:100%"
              >
                <el-option value="mobile" label="移动端" />
                <el-option value="pad" label="PAD" />
                <el-option value="pc" label="PC" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="导航图片" prop="factorName1">
              <el-upload
                class="avatar-uploader"
                :headers="headers"
                :action="picUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="跳转关联:" prop="gotoType">
              <el-select
                v-model="formData.gotoType"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in gotoTypeList"
                  :key="item.dictId"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="formData.gotoType === 'GOODS_CENTER_CATEGORY'" :span="12">
            <el-tree
              ref="tree"
              :data="gotoTreeList"
              show-checkbox
              accordion
              node-key="categoryId"
              :props="defaultProps"
              :default-checked-keys="selectedtreeData"
              @check-change="handleCheckChange"
            />
            <!-- <el-cascader :options="gotoTreeList" :props="props" size="mini" :show-all-levels="false" /> -->
          </el-col>
          <el-col v-if="formData.gotoType === 'GOODS_CENTER_CATEGORY'" :span="24">
            <el-form-item label="筛选模板:" prop="filterId" :rules="filterId">
              <el-select
                v-model="formData.filterId"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in screeningTemList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="formData.gotoType === 'OUTSIDE_LINK'" :span="12">
            <el-input v-model="formData.gotoValue" size="mini" placeholder="请输入外部链接" />
          </el-col>
          <el-col v-if="formData.gotoType === 'APPLY_PAGE'" :span="12">
            <el-select
              v-model="formData.gotoValue"
              size="mini"
              placeholder="请选择"
            >
              <el-option
                v-for="item in gotoValueList"
                :key="item.id"
                :label="item.pageName"
                :value="item.pageUrl"
              />
            </el-select>
          </el-col>
          <el-col v-if="formData.gotoType === 'ATLAS'" :span="12">
            <el-select
              v-model="formData.gotoValue"
              size="mini"
              placeholder="请选择"
            >
              <el-option
                v-for="item in gotoValuepicList"
                :key="item.id"
                :label="item.atlasName"
                :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col v-if="formData.gotoType ==='GOODS_CENTER_CATEGORY'" :span="24">
            <el-form-item label="商品广告" prop="productAdvertisementDTOList">
              <div class="photo-list">
                <!-- <div v-for="(item,index) in adPhotoList" :key="index" class="item-image">
                  <el-image
                    :src="item.fileUrl | filterImageUrl"
                    fit="contain"
                  />
                  <div class="btn-del" @click.stop="deletePhotoHandle(item)">删除</div>
                </div> -->
                <qup-multi-img-uploader
                  ref="refAdUpload"
                  :width="100"
                  :height="100"
                  mask
                  :limit="5"
                  :file-list="uploadImageList"
                  @upload-success="uploadSuccess"
                  @add="addPhotoHandle"
                  @delete="deletePhotoHandle"
                />
              </div>
              <p style="color:#999">建议上传1M以内图片保证更佳显示效果,建议尺寸：1200 x 300。最多可上传5张图片，可拖拽排序。</p>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button size="mini" type="primary" @click="submitForm">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import Sortable from 'sortablejs'
import QupMultiImgUploader from '@/components/imgUploader/multipleUpload'
import { getToken } from '@/utils/auth'
import { saveNav, editNav, getCategoryTree, getAppPageList, getAtlasPic, filterTemplatePage, getSelectTem } from '@/api/shopauxPlat/navConfig' // 新增编辑-保存
export default {
  name: 'DemoEditForm',
  components: { QupMultiImgUploader },
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    },
    sonData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      picUrl: `${process.env.VUE_APP_BASE_API}/api/v1/file/upload`,
      headers: {
        'X-Token': this.$store.getters.token ? getToken() : '',
        'Authorization': this.$store.getters.token ? 'Bearer ' + getToken() : ''
      },
      submiting: false,
      picFile: [],
      gotoTreeList: [],
      screeningTemList: [], // 筛选模板
      selectedtreeData: [],
      pushData: new Set(),
      props: { multiple: true },
      defaultProps: {
        children: 'childList',
        label: 'categoryName'
      },
      imageUrl: '',
      categoryDTOList: [],
      gotoTypeList: [
        { dictId: '01',
          dictName: '商品中心类目',
          dictCode: 'GOODS_CENTER_CATEGORY'
        },
        { dictId: '02',
          dictName: '外部链接',
          dictCode: 'OUTSIDE_LINK'
        },
        { dictId: '03',
          dictName: '应用页面',
          dictCode: 'APPLY_PAGE'
        },
        { dictId: '04',
          dictName: '图册',
          dictCode: 'ATLAS'
        },
        { dictId: '05',
          dictName: '帮助中心',
          dictCode: 'HELP_CENTER'
        }], // 关联类型
      gotoValueList: [], // 应用页面
      gotoValuepicList: [], // 图册
      photoList: [], // 已上传广告图(不可编辑)
      formData: {
        tabName: '',
        state: '1',
        showPlatform: [],
        gotoValue: '',
        filterId: '',
        productAdvertisementDTOList: []
      },
      formRules: {
        tabName: [{
          required: true,
          message: '请输入导航名称',
          trigger: 'blur'
        }],
        state: [{
          required: true,
          message: '请选择是否显示',
          trigger: 'blur'
        }],
        filterId: [{
          required: true,
          message: '请选择筛选模板',
          trigger: 'blur'
        }]
      },
      adPhotoList: []
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    uploadImageList() {
      return this.photoList.map(v => {
        return {
          id: v.id,
          name: v.fileName,
          fileUrl: v.fileUrl,
          url: this.formatImageUrl(v.fileUrl)
        }
      })
    },
    isLevelOne() {
      if (this.detailData && this.detailData.id) {
        return !!this.detailData.isLevelOne
      }
      return !(this.sonData && this.sonData.id)
    }
  },
  watch: {
    'formData.gotoType': {
      handler(val, oldVal) {
        if (val !== oldVal && oldVal !== undefined) {
          this.formData.gotoValue = ''
        }
      }
    }
  },
  created() {
    const data = this.detailData
    if (data.categoryDTOList) {
      data.categoryDTOList.forEach(item => this.selectedtreeData.push(item.categoryId))
      data.categoryDTOList.forEach(item => this.categoryDTOList.push(item))
    }

    const photoList = []
    data.productAdvertisementDTOList && data.productAdvertisementDTOList.forEach((v, i) => {
      photoList.push({
        fileUrl: v.picUrl,
        sort: v.sort,
        id: v.id
      })
    })
    this.photoList = photoList
    this.adPhotoList = [...photoList]

    if (data.state === 1) {
      data.state = '1'
    }
    if (data) {
      this.formData = Object.assign({}, data)
      getSelectTem(data.id).then(res => {
        if (res.success === 1) {
          // this.formData.name = res.data.name
        }
      })
    }
    // 获取基本数据
    this.getBasicData()
  },
  mounted() {
    this.imageUrl = this.formData.picUrl
    this.$nextTick(() => {
      this.openDrag()
    })
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.picFile = file.response.data
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5
      const isJPG = file.type.split('/')[1]
      const allowPic = ['jpg', 'png', 'jpeg']
      if (!allowPic.includes(isJPG)) {
        this.$message.error('上传图片只能是 png/jpg 格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return isJPG && isLt2M
    },
    closeDialog() {
      this.dialogShow = false
    },
    handleCheckChange(data, checked, indeterminate) {
      // 新增
      if (checked && !indeterminate) { // 选中数据时
        if (data.childList && data.childList.length > 0) { // 判断选中数据是否为第一层且有下一层
          data.childList.forEach(item => {
            if (item.childList && item.childList.length > 0) { // 判断选中数据是否为第二层且有下一层
              item.childList.forEach(son => {
                this.pushData.add(son)
              })
              return
            } else {
              this.pushData.add(item)
              return
            }
          })
        } else {
          const val = {}
          val.categoryId = data.categoryId
          val.categoryName = data.categoryName
          this.pushData.add(val)
        }
        if (this.detailData.categoryDTOList) {
          this.categoryDTOList = this.detailData.categoryDTOList.concat([...this.pushData])
        } else {
          this.categoryDTOList = [...this.pushData]
        }
      }
      // 编辑--取消数据
      if (!checked && !indeterminate) {
        if (data.childList && data.childList.length > 0) { // 判断选中数据是否为第一层且有下一层
          data.childList.forEach((item, index) => {
            if (item.childList && item.childList.length > 0) { // 判断选中数据是否为第二层且有下一层
              item.childList.forEach((son, index) => {
                this.categoryDTOList.splice(index, 1)
              })
              return
            } else {
              const cancelData2 = {}
              cancelData2.categoryId = item.categoryId
              this.categoryDTOList.forEach((i, d) => {
                if (i.categoryId === cancelData2.categoryId) {
                  this.categoryDTOList.splice(d, 1)
                }
              })
              return
            }
          })
        } else {
          const cancelData3 = {}
          cancelData3.categoryId = data.categoryId
          this.categoryDTOList.forEach((item, index) => {
            if (item.categoryId === cancelData3.categoryId) {
              this.categoryDTOList.splice(index, 1)
            }
          })
        }
      }
    },
    // 提交表单处理
    submitForm() {
      // 当跳转关联为商品中心类目时,筛选模板必填
      if (this.formData.gotoType === 'GOODS_CENTER_CATEGORY') {
        if (!this.formData.filterId) {
          this.$message.error('筛选模板必填!')
          return
        }
      }
      // this.photoList = this.$refs.refAdUpload.getAllImageList()
      const tabConfigId = this.formData.id || ''
      const productAdvertisementDTOList = this.adPhotoList.map((v, i) => {
        return {
          id: v.id || '',
          picUrl: v.fileUrl,
          sort: i,
          tabConfigId
        }
      })
      // 编辑
      if (this.formData.id) {
        this.formData.picName = this.picFile.fileName
        this.formData.picUrl = this.picFile.url
        this.formData.categoryDTOList = this.categoryDTOList
        const showPlatform = this.formData.showPlatform.join(',')
        const params = { ...this.formData, ...{ showPlatform, productAdvertisementDTOList }}
        editNav(params).then(res => {
          if (res.success === 1) {
            this.$message.success('保存成功')
            this.dialogShow = false
            this.$emit('refreshTable')
          }
        })
      } else { // 新增
        const data = {}
        data.tabName = this.formData.tabName
        data.state = 1
        data.picName = this.picFile.fileName
        data.picUrl = this.picFile.url
        data.gotoValue = this.formData.gotoValue
        data.gotoType = this.formData.gotoType
        data.filterId = this.formData.filterId
        data.categoryDTOList = this.categoryDTOList
        data.productAdvertisementDTOList = productAdvertisementDTOList
        if (this.sonData && this.sonData.id) {
          data.parent = this.sonData.id
        } else {
          const showPlatform = this.formData.showPlatform.join(',')
          data.showPlatform = showPlatform
        }
        saveNav(data).then(res => {
          if (res.success === 1) {
            this.$message.success('保存成功')
            this.dialogShow = false
            this.$emit('refreshTable')
          }
        })
      }
    },
    getBasicData() {
      getCategoryTree().then(res => {
        if (res.success === 1) {
          this.gotoTreeList = res.data
        }
      })
      // 应用页面
      getAppPageList().then(res => {
        if (res.success === 1) {
          this.gotoValueList = res.data
          if (this.detailData.gotoValue) {
            this.gotoValueList.forEach(item => {
              if (item.pageUrl === this.detailData.gotoValue) {
                this.formData.gotoValue = item.pageName
              }
            })
          }
        }
      })
      // 图册
      getAtlasPic().then(res => {
        if (res.success === 1) {
          this.gotoValuepicList = res.data
        }
      })
      // 筛选模板
      filterTemplatePage().then(res => {
        if (res.success === 1) {
          this.screeningTemList = res.data.records
        }
      })
    },
    // 新增广告图
    addPhotoHandle(data) {
      this.adPhotoList.push(data)
      this.formData.productAdvertisementDTOList = this.adPhotoList
      this.$refs.form.validateField('productAdvertisementDTOList')
    },
    // 移除广告图片
    deletePhotoHandle(data) {
      const index = this.adPhotoList.findIndex(v => v.fileUrl === data.fileUrl)
      this.adPhotoList.splice(index, 1)
      this.formData.productAdvertisementDTOList = this.adPhotoList
      this.$refs.form.validateField('productAdvertisementDTOList')
    },
    openDrag() {
      const adItem = this.$refs.refAdUpload && this.$refs.refAdUpload.$el && this.$refs.refAdUpload.$el.querySelector('.el-upload-list')
      this.sortable = adItem && Sortable.create(adItem, {
        animation: 180,
        delay: 0,
        multiDrag: false,
        filter: '.el-upload',
        draggable: '.el-upload-list li',
        handle: '.el-upload-list__item',
        ghostClass: 'dragColbg',
        chosenClass: 'dragColbg',
        onEnd: evt => { // 拖动结束
          if (evt.oldIndex === evt.newIndex) return
          // 处理拖动列数据
          const oldItem = this.adPhotoList[evt.oldIndex]
          this.adPhotoList.splice(evt.oldIndex, 1)
          this.adPhotoList.splice(evt.newIndex, 0, oldItem)
        }
      })
    }
  }
}
</script>
<style lang='scss' scoped>
.el-col el-col-11{margin-bottom: 20px;}
 .avatar-uploader .el-upload {
    border: 1px dashed #181717;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px dashed #181717;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }

.photo-list{
  display: flex;
  flex-wrap: wrap;
  .item-image{
    position: relative;
    width: 100px;
    height: 100px;
    margin-right: 10px;
    margin-bottom: 10px;
    border: 1px solid #d8d8d8;
    overflow: hidden;
    margin-bottom: 5px;
    .el-image{
      width: 98px;
      height: 98px;
    }
    .btn-del{
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      top:0;
      align-items: center;
      justify-content: center;
      background-color: rgba(0,0,0,0.5);
      font-size: 20px;
      color: #fff;
    }
    &:hover .btn-del{
      visibility:visible;
    }
  }
}
</style>
